import 'package:cbec_app/components/base/base_icon.dart';
import 'package:cbec_app/components/base/base_page.dart';
import 'package:cbec_app/components/common/common_style.dart';
import 'package:cbec_app/components/common/consignee_info.dart';
import 'package:cbec_app/components/common/detail_item.dart';
import 'package:cbec_app/components/common/expand_collapse.dart';
import 'package:cbec_app/components/base/base_nav_bar.dart';
import 'package:cbec_app/components/common/recommend.dart';
import 'package:cbec_app/components/goods/goods_info_item.dart';
import 'package:cbec_app/components/popup/after_sales_popup.dart';
import 'package:cbec_app/pages/goods/controller/pending_payment_ctr.dart';
import 'package:cbec_app/pages/goods/view/custom_countdown_timer.dart';
import 'package:cbec_app/routes/routes.dart';
import 'package:cbec_app/utils/AppData.dart';
import 'package:cbec_app/utils/ThemeConfig.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../../components/popup/redpack_popup.dart';

///订单详情

class PendingPaymentPage extends GetView<PendingPaymentController> {
  const PendingPaymentPage({super.key});

  @override
  Widget build(BuildContext context) {
    return GetBuilder<PendingPaymentController>(builder: (controller) {
      return BasePage(
        iconType: IconType.back,
        isIconTitle: controller.isIconTitle,
        title: controller.title,
        tabHeight: controller.tabHeight.h,
        paddingTop: controller.paddingTop.h,
        bgColor: ThemeConfig.bodyColor,
        isShowPadding: true,
        children: [
          // 订单状态
          if (controller.orderInfo != null) TitleStatusWidget(orderInfo: controller.orderInfo!),
          // 物流信息
          if (controller.orderInfo != null) LogisticsBarWidget(orderInfo: controller.orderInfo!),
          // 收货地址
          if (controller.orderInfo != null && controller.orderInfo?['receiveInfo'] != null) ShippingAddressWidget(orderInfo: controller.orderInfo!),

          ///商品信息
          if (controller.orderInfo != null) GoodsInfoDetail(orderInfo: controller.orderInfo!),
          // 价格相关
          if (controller.orderInfo != null && OrderStatus.fromValue(controller.orderInfo?['status']) == OrderStatus.pendingShipment && controller.needPayFinal) ...[
            if (controller.isOrder == 0) ...[
              Column(
                children: [
                  ///价格信息
                  _commonBox(ClipRRect(
                    borderRadius: BorderRadius.all(Radius.circular(8.h)),
                    child: Column(
                      children: [
                        DetailItem(
                          label: '商品总价',
                          content: '￥${controller.data['priceTotal'] ?? ''}',
                        ),
                        DetailItem(
                          label: '税费',
                          content: '￥${controller.data['taxFee'] ?? ''}',
                        ),
                        DetailItem(
                          label: '运费',
                          content: '￥${controller.data['priceExpress'] ?? ''}',
                        ),
                        DetailItem(
                          label: '红包',
                          labelStyle: LabelStyle.labelTitleRed,
                          tagName: '包',
                          content: controller.showRedPackPrice,
                          contentStyle: controller.redPackList.isNotEmpty ? ContentStyle.nextMore : ContentStyle.normal,
                          contentColor: '#e97466',
                          onTap: () {
                            if (controller.redPackList.isNotEmpty) {
                              showRedPackPopup(
                                controller.redPackList,
                                controller.data['priceTotal'],
                                (couponIds, amount) {
                                  controller.useRedPack(couponIds, amount);
                                },
                                controller.useRedPackPrice,
                                controller.useRedPackIds.isEmpty ? 0 : controller.useRedPackIds.length,
                                controller.useRedPackIds,
                              );
                            }
                          },
                        ),

                        // 积分
                        DetailItem(
                          label: '积分（共${controller.pointsInfo['hasPoints'].toString()}分）',
                          content: controller.showPointsPrice,
                          // contentStyle: controller.pointsInfo.isNotEmpty ? ContentStyle.nextMore : ContentStyle.normal,
                          contentStyle: ContentStyle.nextMore,
                          contentColor: '#e97466',
                          onTap: () {
                            controller.selectPointsPay();
                          },
                        ),

                        // 预付卡
                        DetailItem(
                          label: '预付卡（余额：${controller.payCardInfo['hasBdPayCardBalance'].toString()}元）',
                          content: controller.showCardPrice,
                          //contentStyle: controller.payCardInfo.isNotEmpty ? ContentStyle.nextMore : ContentStyle.normal,
                          contentStyle: ContentStyle.nextMore,
                          contentColor: '#e97466',
                          onTap: () {
                            controller.selectCardPay();
                          },
                        ),

                        Container(
                          margin: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                          padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                          decoration: BoxDecoration(
                            color: Tools.fromHex('#f8f8f8'),
                            borderRadius: BorderRadius.circular(5),
                          ),
                          child: Column(
                            children: [
                              Row(
                                children: [
                                  Text(
                                    '●',
                                    style: TextStyle(color: Tools.fromHex('#d8d8d8'), fontSize: 8),
                                  ),
                                  Text('定金¥${controller.orderInfo?['priceOrder']}', style: setTextStyle(14, FontWeight.w300, const Color(0xff3d3d3d))),
                                  const Spacer(),
                                  Text('已付款', style: setTextStyle(14, FontWeight.w300, const Color(0xff3d3d3d))),
                                ],
                              ),
                              const SizedBox(height: 5),
                              Row(
                                children: [
                                  Text(
                                    '●',
                                    style: TextStyle(color: Tools.fromHex('#efbc94'), fontSize: 8),
                                  ),
                                  Text('尾款¥${controller.orderInfo?['finalPay']}', style: setTextStyle(14, FontWeight.w300, Tools.fromHex('#efbc94'))),
                                  const Spacer(),
                                  Text('已开始', style: setTextStyle(14, FontWeight.w300, Tools.fromHex('#efbc94'))),
                                ],
                              ),
                              const SizedBox(height: 5),
                              Row(
                                children: [
                                  Expanded(
                                    child: Text(
                                      '${controller.orderInfo?['presaleEndTime']}前请支付尾款，若有优惠可叠加',
                                      style: setTextStyle(12, FontWeight.w300, const Color(0xff3d3d3d)),
                                      overflow: TextOverflow.ellipsis,
                                      maxLines: 2,
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),
                        Container(
                          margin: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: [
                              Text(
                                '应付尾款',
                                style: setTextStyle(14, FontWeight.w300, Tools.fromHex('#e54f3b')),
                              ),
                              const SizedBox(width: 10),
                              Text(
                                '¥${controller.actualPrice}',
                                style: setTextStyle(15, FontWeight.w700, Tools.fromHex('#e54f3b')),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  )),
                ],
              )
            ] else ...[
              // 锁单样式
              Column(
                children: [
                  ///价格信息
                  _commonBox(ClipRRect(
                    borderRadius: BorderRadius.all(Radius.circular(8.h)),
                    child: Column(
                      children: [
                        DetailItem(
                          label: '商品总价',
                          content: '￥${controller.data['priceTotal'] ?? ''}',
                        ),
                        DetailItem(
                          label: '税费',
                          content: '￥${controller.data['taxFee'] ?? ''}',
                        ),
                        DetailItem(
                          label: '运费',
                          content: '￥${controller.data['priceExpress'] ?? ''}',
                        ),

                        // 商品促销
                        getPriceGoodsDiscountStyle(),
                        // 会员优惠
                        getVipStyle(),
                        // 活动优惠（秒杀、特价、拼团、砍价、预售等）
                        getDiscountStyle(),
                        // 整单促销
                        getFullDiscount(),
                        // 优惠卷
                        getCouponPriceStyle(),
                        // 红包
                        getRedPackPriceStyle(),

                        // 积分
                        DetailItem(
                          label: '积分',
                          labelStyle: LabelStyle.normal,
                          content: controller.type == 5 ? '-￥${controller.extra['finalPointsMoney']}' : '-￥${controller.extra['pointsMoney']}',
                          contentStyle: ContentStyle.normal,
                          // contentColor: '#e97466',
                        ),

                        // 预付卡
                        DetailItem(
                          label: '预付卡',
                          content: controller.type == 5 ? '-￥${controller.extra['finalUseBdPayCard']}' : '-￥${controller.extra['useBdPayCard']}',
                          contentStyle: ContentStyle.normal,
                        ),

                        SizedBox(height: 10.h),

                        Container(
                          margin: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                          padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                          decoration: BoxDecoration(
                            color: Tools.fromHex('#f8f8f8'),
                            borderRadius: BorderRadius.circular(5),
                          ),
                          child: Column(
                            children: [
                              Row(
                                children: [
                                  Text(
                                    '●',
                                    style: TextStyle(color: Tools.fromHex('#d8d8d8'), fontSize: 8),
                                  ),
                                  Text('定金¥${controller.orderInfo?['priceOrder']}', style: setTextStyle(14, FontWeight.w300, const Color(0xff3d3d3d))),
                                  const Spacer(),
                                  Text('已付款', style: setTextStyle(14, FontWeight.w300, const Color(0xff3d3d3d))),
                                ],
                              ),
                              const SizedBox(height: 5),
                              Row(
                                children: [
                                  Text(
                                    '●',
                                    style: TextStyle(color: Tools.fromHex('#efbc94'), fontSize: 8),
                                  ),
                                  Text('尾款¥${controller.orderInfo?['finalPay']}', style: setTextStyle(14, FontWeight.w300, Tools.fromHex('#efbc94'))),
                                  const Spacer(),
                                  Text('已开始', style: setTextStyle(14, FontWeight.w300, Tools.fromHex('#efbc94'))),
                                ],
                              ),
                              const SizedBox(height: 5),
                              Row(
                                children: [
                                  Expanded(
                                    child: Text(
                                      '${controller.orderInfo?['presaleEndTime']}前请支付尾款，若有优惠可叠加',
                                      style: setTextStyle(12, FontWeight.w300, const Color(0xff3d3d3d)),
                                      overflow: TextOverflow.ellipsis,
                                      maxLines: 2,
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),

                        Container(
                          margin: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: [
                              Text(
                                '应付尾款',
                                style: setTextStyle(14, FontWeight.w300, Tools.fromHex('#e54f3b')),
                              ),
                              const SizedBox(width: 10),
                              Text(
                                '¥${controller.prepareFinalPayMap['pricePay']}',
                                style: setTextStyle(15, FontWeight.w700, Tools.fromHex('#e54f3b')),
                              ),
                            ],
                          ),
                        )
                      ],
                    ),
                  )),
                ],
              )
            ],
          ] else ...[
            if (controller.orderInfo != null) buildGoodMoneyWidget(controller),
          ],
          //订单信息
          if (controller.orderInfo != null) BaseOrderInfoWidget(orderInfo: controller.orderInfo!, controller: controller),
          Recommend(location: "OrderDetail"),
          emptyMargin(70),
          if (controller.orderInfo != null)
            Positioned(
              left: 0,
              bottom: MediaQuery.of(context).padding.bottom,
              right: 10,
              height: 60,
              child: Container(
                color: Colors.white,
                child: BottomButtonsStyleWidget(controller: controller, orderInfo: controller.orderInfo!),
              ),
            ),
        ],
      );
    });
  }

  // 商品总价这块
  Widget buildGoodMoneyWidget(PendingPaymentController controller) {
    return Column(
      children: [
        ///价格信息
        _commonBox(ClipRRect(
          borderRadius: BorderRadius.all(Radius.circular(8.h)),
          child: Column(
            children: [
              DetailItem(
                label: '商品总价',
                content: '￥${controller.data['priceTotal'] ?? ''}',
              ),
              DetailItem(
                label: '税费',
                content: '￥${controller.data['taxFee'] ?? ''}',
              ),
              DetailItem(
                label: '运费',
                content: '￥${controller.data['priceExpress'] ?? ''}',
              ),

              // 商品促销
              getPriceGoodsDiscountStyle(),
              // 会员优惠
              getVipStyle(),
              // 活动优惠（秒杀、特价、拼团、砍价、预售等）
              getDiscountStyle(),
              // 整单促销
              getFullDiscount(),
              // 优惠卷
              getCouponPriceStyle(),
              // 红包
              getRedPackPriceStyle(),
              // 预付卡
              getUseBdPayCard(),
              // 积分
              getPointsMoneyStyle(),

              SizedBox(height: 10.h),
            ],
          ),
        )),
        //总价信息
        Container(
          padding: EdgeInsets.only(top: 11.h),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              Container(
                margin: EdgeInsets.only(left: 5.w, right: 10.w),
                child: Text(
                  '总计',
                  style: setTextStyle(13, FontWeight.w400, ThemeConfig.themeColor),
                ),
              ),
              Text(
                '¥${controller.data['priceOrder'].toString()}',
                style: setTextStyle(13, FontWeight.w500, ThemeConfig.themeColor),
              )
            ],
          ),
        ),
      ],
    );
  }

  ///获取会员优惠样式
  Widget getVipStyle() {
    if (controller.extra['vipDiscount'] != null && controller.extra['vipDiscount'] > 0) {
      return DetailItem(
        label: '会员优惠',
        labelStyle: LabelStyle.labelTitleRed,
        tagName: '会',
        content: '-￥${controller.extra['vipDiscount'].toString()}',
      );
    } else {
      return emptyWidget();
    }
  }

  /// 整单优惠
  Widget getFullDiscount() {
    return Visibility(
      visible: (controller.extra['fullDiscount'] != null && controller.extra['fullDiscount'] > 0),
      child: DetailItem(
        label: '整单优惠',
        labelStyle: LabelStyle.labelTitleRed,
        tagName: '整',
        content: '-￥${controller.extra['fullDiscount'].toString()}',
      ),
    );
  }

  ///商品促销
  Widget getPriceGoodsDiscountStyle() {
    return Visibility(
      visible: (controller.extra['goodsDiscount'] != null && controller.extra['goodsDiscount'] > 0),
      child: DetailItem(
        label: '商品促销',
        labelStyle: LabelStyle.labelTitleYellow,
        tagName: '促',
        content: '-￥${controller.extra['goodsDiscount'].toString()}',
      ),
    );
  }

  /// 优惠券
  Widget getCouponPriceStyle() {
    return Visibility(
      visible: (controller.extra['couponDiscount'] != null && controller.extra['couponDiscount'] > 0),
      child: DetailItem(
        label: '优惠券',
        labelStyle: LabelStyle.labelTitleRed,
        tagName: '券',
        content: '-￥${controller.extra['couponDiscount'].toString()}',
        contentStyle: ContentStyle.normal,
      ),
    );
  }

  /// 红包
  Widget getRedPackPriceStyle() {
    return Visibility(
      visible: (controller.extra['redPacketMoney'] != null),
      child: DetailItem(
        label: '红包',
        labelStyle: LabelStyle.labelTitleRed,
        tagName: '包',
        content: '-￥${controller.extra['redPacketMoney'].toString()}',
        contentStyle: ContentStyle.normal,
        // contentColor: '#e97466',
      ),
    );
  }

  /// 积分抵扣金额
  Widget getPointsMoneyStyle() {
    return DetailItem(
      label: '积分',
      labelStyle: LabelStyle.normal,
      content: controller.type == 5 ? '-￥${controller.extra['finalPointsMoney']}' : '-￥${controller.extra['pointsMoney']}',
      contentStyle: ContentStyle.normal,
      // contentColor: '#e97466',
    );
  }

  /// 预付卡
  Widget getUseBdPayCard() {
    return DetailItem(
      label: '预付卡',
      content: controller.type == 5 ? '-￥${controller.extra['finalUseBdPayCard']}' : '-￥${controller.extra['useBdPayCard']}',
      contentStyle: ContentStyle.normal,
    );
  }

  ///活动优惠
  Widget getDiscountStyle() {
    return calculateActivityDiscount() > 0
        ? DetailItem(
            label: '活动优惠',
            labelStyle: LabelStyle.labelTitleYellow,
            tagName: '活',
            content: '-￥${calculateActivityDiscount().toString()}',
          )
        : const SizedBox();
  }

  double calculateActivityDiscount() {
    // 活动类型
    var activityDiscount = 0.0;
    //print('活动类型 ===== ${controller.orderInfo?['type']}');
    if (controller.data['type'] == null) {
      return activityDiscount;
    }
    int type = controller.orderInfo?['type'];

    switch (type) {
      case 0:
        break;
      case 2:
        activityDiscount = controller.extra['specialDiscount'];
        break;
      case 3:
        activityDiscount = controller.extra['orderActivityDiscount'];
        break;
      case 4:
        activityDiscount = controller.extra['orderActivityDiscount'];
        break;
      case 5:
        activityDiscount = controller.extra['orderActivityDiscount'];
        break;
      case 6:
        break;
      case 7:
        break;
      case 8:
        activityDiscount = controller.extra['orderActivityDiscount'];
        break;
      case 9:
        activityDiscount = controller.extra['newUserDiscount'];
        break;
      default:
    }

    return activityDiscount;
  }

  // 总过减多少钱
  double totalDiscount() {
    var total = calculateActivityDiscount() + controller.extra['useBdPayCard'] + controller.extra['redPacketMoney'] + controller.extra['pointsMoney'] + controller.extra['vipDiscount'] + controller.extra['goodsDiscount'] + controller.extra['couponDiscount'];
    return total;
  }
}

// 订单状态
class TitleStatusWidget extends StatefulWidget {
  final Map orderInfo;

  const TitleStatusWidget({super.key, required this.orderInfo});

  @override
  State<TitleStatusWidget> createState() => _TitleStatusWidgetState();
}

/// 标题状态
class _TitleStatusWidgetState extends State<TitleStatusWidget> {
  late OrderStatus status;

  // 是否是预售单
  late bool isPreSale;

  // 预售订单类型 1-全款预售 2-定金预售
  late int presaleType;

  // 是否已付尾款 0-否 1-是
  late int finalStatus;

  // 付尾款结束时间
  late String presaleEndTime;

  @override
  void initState() {
    super.initState();
    status = OrderStatus.fromValue(widget.orderInfo['status']);
    isPreSale = widget.orderInfo['type'] == 5;
    presaleType = widget.orderInfo['presaleType'];
    finalStatus = widget.orderInfo['finalStatus'];
    presaleEndTime = widget.orderInfo['presaleEndTime'] ?? '';
  }

  /// 是否是定金预售，还未支付尾款
  bool isPayFinal() {
    return isPreSale && presaleType == 2 && finalStatus == 0;
  }

  @override
  Widget build(BuildContext context) {
    String statusText;
    TextStyle textStyle = TextStyle(
      color: Tools.fromHex('#333333'),
      fontSize: 18,
      fontWeight: FontWeight.bold,
    );

    switch (status) {
      case OrderStatus.canceled:
        statusText = '已取消';
        break;
      case OrderStatus.pendingPayment:
        statusText = '待支付';
        break;
      case OrderStatus.pendingShipment:
        statusText = isPayFinal() ? '待付尾款' : '正在出库';
        break;
      case OrderStatus.shipped:
        statusText = '等待收货';
        break;
      case OrderStatus.completed:
        statusText = '已完成';
        break;
      default:
        return const SizedBox();
    }

    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(statusText, style: textStyle),
          if (status == OrderStatus.canceled) Text('取消原因：${widget.orderInfo['cancelReason']}'),
          if (status == OrderStatus.pendingPayment) _buildWaitPayTextWidget(),
          if (status == OrderStatus.pendingShipment && isPayFinal()) _buildWaitPayTextWidget(),
        ],
      ),
    );
  }

  Widget _buildWaitPayTextWidget() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text(
          presaleEndTime,
          style: setTextStyle(12, FontWeight.w400, const Color(0xff3d3d3d)),
        ),
        Text(
          '订单自动取消',
          style: setTextStyle(12, FontWeight.w400, const Color(0xff3d3d3d)),
        )
      ],
    );
  }

  Widget _buildPayFinalTextWidget() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text(
          '还剩',
          style: setTextStyle(12, FontWeight.w400, const Color(0xff3d3d3d)),
        ),
        CustomCountdownTimer(endTime: DateTime.parse(widget.orderInfo['cd'] ?? '').add(const Duration(minutes: 15)), onEnd: () {}),
        Text(
          '前请支付尾款',
          style: setTextStyle(12, FontWeight.w400, const Color(0xff3d3d3d)),
        )
      ],
    );
  }
}

/// 商品信息
class GoodsInfoDetail extends StatefulWidget {
  final Map orderInfo;

  const GoodsInfoDetail({super.key, required this.orderInfo});

  @override
  State<GoodsInfoDetail> createState() => _GoodsInfoDetailState();
}

class _GoodsInfoDetailState extends State<GoodsInfoDetail> {
  late List goodsInfo;

  @override
  void initState() {
    super.initState();
    goodsInfo = widget.orderInfo['goodsInfo'];
  }

  @override
  Widget build(BuildContext context) {
    return _commonBox(ClipRRect(
      borderRadius: BorderRadius.all(Radius.circular(8.h)),
      child: Column(
        children: [
          goodsInfo.isNotEmpty
              ? Column(
                  children: List.generate(goodsInfo.length, (index) {
                    Map<String, dynamic> item = goodsInfo[index];
                    return GoodsInfoItem(goodsInfo: item, infoStyle: InfoStyle.settlement);
                  }),
                )
              : const SizedBox(),
          _customer(),
        ],
      ),
    ));
  }
}

// 物流信息
class LogisticsBarWidget extends StatefulWidget {
  final Map orderInfo;

  const LogisticsBarWidget({super.key, required this.orderInfo});

  @override
  State<LogisticsBarWidget> createState() => _LogisticsBarWidgetState();
}

class _LogisticsBarWidgetState extends State<LogisticsBarWidget> {
  late OrderStatus status;
  late Map expressInfo;
  late String expressName;
  late String expressCode;

  @override
  void initState() {
    super.initState();
    status = OrderStatus.fromValue(widget.orderInfo['status']);
    expressInfo = widget.orderInfo['expressInfo'] ?? {};
    expressName = widget.orderInfo['expressName'] ?? '';
    expressCode = widget.orderInfo['expressCode'] ?? '';
  }

  Widget _buildLogisticsInfoWidget() {
    return GestureDetector(
      onTap: () {
        Get.toNamed(Routes.expressDetailInfoPage, arguments: widget.orderInfo);
      },
      child: Container(
        margin: const EdgeInsets.symmetric(vertical: 10),
        padding: const EdgeInsets.all(10),
        height: 60.h,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10),
          color: Colors.white,
        ),
        child: Row(
          children: [
            Row(
              children: [
                Image.asset(
                  "assets/images/logistics_car.png",
                  fit: BoxFit.cover,
                  width: 30,
                  height: 30,
                  color: Tools.fromHex('#5094e5'),
                ),
                const SizedBox(width: 10),
                Text(
                  expressName,
                  style: TextStyle(color: Tools.fromHex('#5094e5')),
                ),
                Text(
                  expressCode,
                  style: TextStyle(color: Tools.fromHex('#5094e5')),
                ),
              ],
            ),
            const Spacer(),
            const Icon(
              Icons.navigate_next_outlined,
              color: Colors.grey,
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    switch (status) {
      case OrderStatus.shipped:
      case OrderStatus.completed:
        return _buildLogisticsInfoWidget();
      default:
        return const SizedBox();
    }
  }
}

/// 收货地址组件
class ShippingAddressWidget extends StatefulWidget {
  final Map orderInfo;

  const ShippingAddressWidget({super.key, required this.orderInfo});

  @override
  State<ShippingAddressWidget> createState() => _ShippingAddressWidgetState();
}

class _ShippingAddressWidgetState extends State<ShippingAddressWidget> {
  late String receiveName;
  late String receiveMobile;
  late String receiveAddress;

  @override
  void initState() {
    receiveName = widget.orderInfo['receiveName'] ?? '';
    receiveMobile = widget.orderInfo['receiveMobile'] ?? '';
    receiveAddress = widget.orderInfo['receiveAddress'] ?? '';

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return ConsigneeInfo(
      isCanTap: false,
      receiveName: receiveName,
      receiveMobile: receiveMobile,
      receiveAddress: receiveAddress,
      receiveInfo: '',
      btnType: EditBtnType.none,
    );
  }
}

// 订单信息
class BaseOrderInfoWidget extends StatefulWidget {
  final PendingPaymentController controller;
  final Map orderInfo;

  const BaseOrderInfoWidget({super.key, required this.orderInfo, required this.controller});

  @override
  State<BaseOrderInfoWidget> createState() => _BaseOrderInfoWidgetState();
}

class _BaseOrderInfoWidgetState extends State<BaseOrderInfoWidget> {
  late OrderStatus status;
  late String sn;
  late int payType;
  late String priceOrder;
  late String cd;
  late int shippingType;
  late String payTime;

  @override
  void initState() {
    super.initState();
    status = OrderStatus.fromValue(widget.orderInfo['status']);
    sn = widget.orderInfo['sn'] ?? '';
    priceOrder = widget.orderInfo['priceOrder'].toString();
    cd = widget.orderInfo['cd'] ?? '';
    shippingType = widget.orderInfo['shipping_type'] ?? 0;
    payType = widget.orderInfo['payType'] ?? 0;
    payTime = widget.orderInfo['payTime'] ?? '';
  }

  List<Widget> _buildOrderDetails() {
    List<Widget> details = [
      DetailItem(
        label: '订单编号',
        content: '$sn复制',
        contentStyle: ContentStyle.order,
        onTap: () {
          widget.controller.copy(sn);
        },
      ),
    ];

    if (status != OrderStatus.canceled && status != OrderStatus.pendingPayment) {
      details.addAll([
        DetailItem(
          label: '支付方式',
          content: Tools.getPaymentType(payType),
          contentStyle: ContentStyle.order,
        ),
        DetailItem(
          label: '实付款',
          content: '¥$priceOrder',
          contentStyle: ContentStyle.order,
        ),
        DetailItem(
          label: '支付时间',
          content: payTime,
          contentStyle: ContentStyle.order,
        ),
      ]);
    }

    details.add(
      DetailItem(
        label: '下单时间',
        content: cd,
        contentStyle: ContentStyle.order,
      ),
    );

    if (status != OrderStatus.canceled && status != OrderStatus.pendingPayment) {
      details.add(
        DetailItem(
          label: '配送方式',
          content: Tools.getTransportType(shippingType),
          contentStyle: ContentStyle.order,
        ),
      );
    }

    return details;
  }

  @override
  Widget build(BuildContext context) {
    return _commonBox(
      ExpandCollapse(
        heightFactor: 1,
        leftText: '订单信息',
        children: _buildOrderDetails(),
      ),
    );
  }
}

class BottomButtonsStyleWidget extends StatefulWidget {
  final PendingPaymentController controller;
  final Map orderInfo;

  const BottomButtonsStyleWidget({super.key, required this.controller, required this.orderInfo});

  @override
  State<BottomButtonsStyleWidget> createState() => _BottomButtonsStyleWidgetState();
}

class _BottomButtonsStyleWidgetState extends State<BottomButtonsStyleWidget> {
  // 是否是预售单
  late bool isPreSale;

  // 预售订单类型 1-全款预售 2-定金预售
  late int presaleType;

  // 是否已付尾款 0-否 1-是
  late int finalStatus;

  // 预售状态 0-还没有到付尾款时间 1-正在进行尾款 2-尾款付款时间已结束
  late int presaleStatus;

  late OrderStatus status;

  late List goodsInfo;

  bool needPayFinal = false;

  @override
  void initState() {
    super.initState();
    status = OrderStatus.fromValue(widget.orderInfo['status']);
    isPreSale = widget.orderInfo['type'] == 5;
    presaleType = widget.orderInfo['presaleType'];
    goodsInfo = widget.orderInfo['goodsInfo'];
    finalStatus = widget.orderInfo['finalStatus'];
    bool boolValue = isPreSale && presaleType == 2 && finalStatus == 0;
    if (isPreSale) {
      // 预售状态 0-还没有到付尾款时间 1-正在进行尾款 2-尾款付款时间已结束
      int presaleStatus = widget.orderInfo['presaleStatus'];
      bool isPayFinal = presaleStatus == 1;
      needPayFinal = boolValue && isPayFinal;
    }
  }

  @override
  Widget build(BuildContext context) {
    switch (status) {
      case OrderStatus.canceled:
        if (isPreSale) {
          return const SizedBox();
        } else {
          return Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              solidButton(
                "删除订单",
                backgroundColor: Colors.white,
                borderColor: Tools.fromHex("#D7D7D7"),
                textColor: Colors.black,
                fontsize: 13,
                width: 72.w,
                height: 28.w,
                () {
                  widget.controller.deleteOrder();
                },
              ),
              const SizedBox(width: 10),
              solidButton(
                "再次购买",
                backgroundColor: Colors.white,
                borderColor: Tools.fromHex("#F83F2D"),
                textColor: Tools.fromHex("#F83F2D"),
                fontsize: 13,
                width: 72.w,
                height: 28.w,
                () {
                  widget.controller.argin(
                    widget.controller.goodsInfo,
                    widget.controller.orderInfo?['type'],
                  );
                },
              ),
            ],
          );
        }
      case OrderStatus.pendingPayment: // 待支付
        if (isPreSale) {
          if (presaleType == 1) {
            // 全款预售
            return Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                solidButton("立即支付", width: 90.w, radius: 30, () {
                  Get.toNamed(
                    '${Routes.cashier}/?sn=${widget.orderInfo['paySn']}&price=${widget.orderInfo['priceOrder']}&cd=${widget.orderInfo['cd']}',
                    arguments: {'hasBonded': widget.controller.hasBonded},
                  );
                }),
              ],
            );
          } else {
            return Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Container(
                  padding: const EdgeInsets.only(left: 10),
                  child: Text(
                    '定金：¥${widget.controller.orderInfo?['priceOrder'].toString()}',
                    style: TextStyle(
                      color: Tools.fromHex('#F83F2D'),
                      fontSize: 14,
                    ),
                  ),
                ),
                solidButton("支付定金", width: 90.w, radius: 30, () {
                  Get.toNamed(
                    '${Routes.cashier}/?sn=${widget.orderInfo['paySn']}&price=${widget.orderInfo['priceOrder']}&cd=${widget.orderInfo['cd']}',
                    arguments: {'hasBonded': widget.controller.hasBonded},
                  );
                }),
              ],
            );
          }
        } else {
          // 非预售待支付
          return Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              solidButton("立即支付", width: 90.w, radius: 30, () {
                Get.toNamed(
                  '${Routes.cashier}/?sn=${widget.orderInfo['paySn']}&price=${widget.orderInfo['priceOrder']}&cd=${widget.orderInfo['cd']}',
                  arguments: {'hasBonded': widget.controller.hasBonded},
                );
              }),
            ],
          );
        }
      case OrderStatus.pendingShipment:
        if (isPreSale) {
          if (presaleType == 1) {
            return const SizedBox();
          } else {
            if (finalStatus == 0) {
              return Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  solidButton(
                    "支付尾款",
                    backgroundColor: Colors.white,
                    borderColor: Tools.fromHex("#D7D7D7"),
                    textColor: Colors.black,
                    fontsize: 13,
                    width: 72.w,
                    height: 28.w,
                    () {
                      if (needPayFinal) {
                        widget.controller.payPlaceOrderFinalPay();
                      }
                    },
                  ),
                ],
              );
            } else {
              return Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  solidButton(
                    "申请售后",
                    backgroundColor: Colors.white,
                    borderColor: Tools.fromHex("#D7D7D7"),
                    textColor: Colors.black,
                    fontsize: 13,
                    width: 72.w,
                    height: 28.w,
                    () {
                      afterSalesPopup(context, goodsInfo, widget.orderInfo['id'], afterSaleStyle: 2);
                    },
                  ),
                ],
              );
            }
          }
        } else {
          return Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              solidButton(
                "申请售后",
                backgroundColor: Colors.white,
                borderColor: Tools.fromHex("#D7D7D7"),
                textColor: Colors.black,
                fontsize: 13,
                width: 72.w,
                height: 28.w,
                () {
                  afterSalesPopup(context, goodsInfo, widget.orderInfo['id'], afterSaleStyle: 2);
                },
              ),
            ],
          );
        }
      case OrderStatus.shipped:
        return Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            if (!isPreSale) ...[
              solidButton(
                "申请售后",
                backgroundColor: Colors.white,
                borderColor: Tools.fromHex("#D7D7D7"),
                textColor: Colors.black,
                fontsize: 13,
                width: 72.w,
                height: 28.w,
                () {
                  afterSalesPopup(context, widget.controller.goodsInfo, widget.controller.orderInfo?['id'], afterSaleStyle: 1);
                },
              ),
              const SizedBox(width: 10),
            ],
            solidButton(
              "确认收货",
              backgroundColor: Colors.white,
              borderColor: Tools.fromHex("#F83F2D"),
              textColor: Tools.fromHex("#F83F2D"),
              fontsize: 13,
              width: 72.w,
              height: 28.w,
              () {
                widget.controller.receive(widget.orderInfo['id']);
              },
            ),
          ],
        );
      case OrderStatus.completed:
        if (isPreSale) {
          if (presaleType == 2) {
            return Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                solidButton(
                  "申请售后",
                  backgroundColor: Colors.white,
                  borderColor: Tools.fromHex("#D7D7D7"),
                  textColor: Colors.black,
                  fontsize: 13,
                  width: 72.w,
                  height: 28.w,
                  () {
                    afterSalesPopup(context, widget.controller.goodsInfo, widget.controller.orderInfo?['id'], afterSaleStyle: 2);
                  },
                ),
              ],
            );
          } else {
            return const SizedBox();
          }
        } else {
          return Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              solidButton(
                "再次购买",
                backgroundColor: Colors.white,
                borderColor: Tools.fromHex("#F83F2D"),
                textColor: Tools.fromHex("#F83F2D"),
                fontsize: 13,
                width: 72.w,
                height: 28.w,
                () {
                  widget.controller.argin(
                    widget.controller.goodsInfo,
                    widget.controller.orderInfo?['type'],
                  );
                },
              ),
              const SizedBox(width: 10),
              solidButton(
                "申请售后",
                backgroundColor: Colors.white,
                borderColor: Tools.fromHex("#D7D7D7"),
                textColor: Colors.black,
                fontsize: 13,
                width: 72.w,
                height: 28.w,
                () {
                  afterSalesPopup(context, widget.controller.goodsInfo, widget.controller.orderInfo?['id'], afterSaleStyle: 1);
                },
              ),
            ],
          );
        }
      default:
        return const SizedBox();
    }
  }
}

///通用容器
Widget _commonBox(Widget child) {
  return Container(
    margin: EdgeInsets.only(top: 10.h),
    decoration: BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(8.h)), color: Colors.white),
    child: child,
  );
}

///客服
Widget _customer() {
  return InkWell(
    onTap: () {
      Get.toNamed(Routes.serviceSupportPage);
    },
    child: Container(
      height: 39.h,
      color: Colors.white,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const BaseIcon(
            url: 'customer.png',
            size: 13,
          ),
          Padding(
            padding: EdgeInsets.only(left: 3.w),
            child: Text(
              '联系客服',
              style: setTextStyle(13, FontWeight.w500, ThemeConfig.mainTextColor),
            ),
          )
        ],
      ),
    ),
  );
}
